package com.dji.system.core.nio;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dji.bean.Autowired;
import com.dji.bean.Compoment;
import com.dji.system.core.NIOClient;

@Compoment
public class IoServiceAdapter implements IoServiceListener {
	private final static Logger log = LoggerFactory.getLogger(IoServiceAdapter.class);
	@Autowired
	private NIOClient client;
	private SocketConnector connector;
	private ConnectFuture future;

	public void serviceActivated(IoService arg0) throws Exception {

	}

	public void serviceDeactivated(IoService arg0) throws Exception {

	}

	public void serviceIdle(IoService arg0, IdleStatus arg1) throws Exception {

	}

	public void sessionClosed(IoSession arg0) throws Exception {

	}

	public void sessionCreated(IoSession arg0) throws Exception {
		log.debug("窗帘了");
	}

	public void sessionDestroyed(IoSession session) throws Exception {
		while (true) {
			try {
				connector = client.getConnector();
				future = connector.connect(new InetSocketAddress(8080));
				future.awaitUninterruptibly();
				session = future.getSession();
				if (session.isConnected()) {
					log.debug("重新连接上");
					return;
				} else {
					log.debug("连接失败");
					Thread.sleep(2000);
				}
			} catch (Exception e) {
				log.debug("连接失败");
				Thread.sleep(2000);
			}
		}
	}

}
